package net.xdclass.service.impl;

import lombok.extern.slf4j.Slf4j;
import net.xdclass.constant.CacheKey;
import net.xdclass.enums.BizCodeEnum;
import net.xdclass.enums.SendCodeEnum;
import net.xdclass.exception.BizException;
import net.xdclass.service.MailService;
import net.xdclass.service.NotifyService;
import net.xdclass.util.CheckUtil;
import net.xdclass.util.CommonUtil;
import net.xdclass.util.JsonData;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @Classname NotifyServiceImpl
 * @Description TODO
 * @Date 2022/4/7 14:17
 * @Created by sunhao
 */
@Slf4j
@Service
public class NotifyServiceImpl implements NotifyService {

  @Autowired
  private MailService mailService;

  @Autowired
  private StringRedisTemplate redisTemplate;

  private static final String SUBJECT = "神域集团验证码";

  private static final String CONTENT = "您的验证码是%s,有效时间是60秒,打死也不要告诉任何人!";

  private static final int CODE_EXPIRED = 60 * 1000 * 10;

  @Override
  public JsonData sendCode(SendCodeEnum sendCodeEnum, String mailTo) {
    String cacheKey = String.format(CacheKey.CHECK_CODE_KEY, sendCodeEnum.name(), mailTo);

    String cacheValue = redisTemplate.opsForValue().get(cacheKey);

    if (StringUtils.isNotEmpty(cacheValue)) {
      long ttl = Long.parseLong(cacheValue.split("_")[1]);

      if (CommonUtil.getCurrentTimestamp() - ttl < 1000 * 60) {
        log.info("重复发送验证码,时间间隔{}", (CommonUtil.getCurrentTimestamp() - ttl) / 1000);
        throw new BizException(BizCodeEnum.MAIL_TO_ERROR);
      }
    }
    //拼接验证码
    String code = CommonUtil.getRandomCode(6);
    String value = code + "_" + CommonUtil.getCurrentTimestamp();
    redisTemplate.opsForValue().set(cacheKey, value, CODE_EXPIRED, TimeUnit.MILLISECONDS);

    if (CheckUtil.isEmail(mailTo)) {
      //邮箱验证码
      mailService.sendMail(mailTo, SUBJECT, String.format(CONTENT, code));
    } else if (CheckUtil.isPhone(mailTo)) {
      //手机验证码

    } else {
      throw new BizException(BizCodeEnum.MAIL_TO_ERROR);
    }
    return JsonData.buildSuccessMessage("发送成功");
  }

  @Override
  public boolean checkCode(SendCodeEnum sendCodeEnum, String to, String code) {
    String cacheKey = String.format(CacheKey.CHECK_CODE_KEY, sendCodeEnum.name(), to);
    String cacheValue = redisTemplate.opsForValue().get(cacheKey);
    if (StringUtils.isEmpty(cacheValue)) {
      return false;
    }
    String cacheCode = cacheValue.split("_")[0];
    if (!cacheCode.equals(code)) {
      return false;
    }
    return true;
  }
}
